package hrms.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import hrms.entity.Account;

import java.util.Date;

public class JWTUtil {

    //加密算法
    private static final String SECRET = "SomethingRight";

    // 过期时间5分钟
    private static final long EXPIRE_TIME = 5*60*1000;

    private static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET);


    /**
     * 获取token中的username
     * @param token
     * @return
     */
    public static String getId(String token){
        try{
            //token中有username信息
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaim("id").asString();
        }catch (Exception e){
            //token中没有username信息
            return null;
        }
    }

    /**
     * 校验token是否正确
     * @param token 密钥
     * @param account 用户
     * @return 是否正确
     */
    public static boolean verify(String token, Account account){
        try{

            JWTVerifier verifier = JWT.require(ALGORITHM)
                    //校验username,password是否正确
                    .withClaim("id", account.getId())
                    .withClaim("password",account.getPassword())
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 生成签名,5min后过期
     * @param account 用户
     * @return 加密的token
     */
    public static String sign(Account account){
        try{
//            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            //附带username、password信息
            return JWT.create()
                    .withClaim("id",account.getId().toString())
                    .withClaim("password",account.getPassword())
                    .sign(ALGORITHM);
        }catch (Exception e){
            return null;
        }
    }


}
